package org.javaboy.servlet;

import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * asyncSupported = true 开启异步支持
 */
@WebServlet(value = "/hello2",asyncSupported = true)
public class HelloServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //开启异步处理
        AsyncContext asyncContext = req.startAsync();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //睡眠相当于模拟 service 和 dao 层执行时间
                try {
                    Thread.sleep(2000);
                    asyncContext.getResponse().getWriter().write("hello");
                    asyncContext.complete();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
